// app.ts
interface ImageItem {
  id: string;
  prompt: string;
  imageUrl: string;
  height?: number;
  createdAt: number;
}

// 扩展微信UserInfo类型，添加云数据库相关字段
interface CloudUserInfo extends WechatMiniprogram.UserInfo {
  _id?: string;
  openId?: string;
  createTime?: Date;
  lastLoginTime?: Date;
  updateTime?: Date;
  imageCount?: number;
}

interface IGlobalData {
  userInfo: CloudUserInfo | null;
  hasUserInfo: boolean;
  canIUseProfile: boolean;
  isLoggedIn: boolean;
  newPublishedImage?: ImageItem;
  cloudEnvId: string;
}

App<{
  globalData: IGlobalData;
  checkLoginStatus: () => Promise<void>;
}>({
  globalData: {
    userInfo: null,
    hasUserInfo: false,
    canIUseProfile: wx.canIUse('button.open-type.getUserInfo'),
    isLoggedIn: false,
    cloudEnvId: 'cloud1-9g0y3xq2422bb278'
  },
  onLaunch() {
    // 初始化云开发
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力');
    } else {
      wx.cloud.init({
        env: this.globalData.cloudEnvId,
        traceUser: true,
      });
      console.log('云开发初始化成功');
    }

    // 检查登录状态
    this.checkLoginStatus();
  },

  async checkLoginStatus() {
    try {
      // 首先尝试从本地获取用户信息，优先使用本地缓存
      const localUserInfo = wx.getStorageSync('userInfo');
      if (localUserInfo) {
        console.log('从本地缓存获取用户信息成功:', localUserInfo);
        this.globalData.userInfo = localUserInfo;
        this.globalData.hasUserInfo = true;
        this.globalData.isLoggedIn = true;
        
        // 尝试在后台与服务器同步，但不依赖结果
        this.syncUserWithServer(localUserInfo);
        return;
      }
      
      // 如果本地没有，尝试从服务器获取
      const loginState = await wx.cloud.callFunction({
        name: 'checkLogin',
      });
      
      console.log('登录状态检查:', loginState);
      
      // @ts-ignore
      if (loginState.result && loginState.result.isLogin && loginState.result.userInfo) {
        // @ts-ignore
        const userInfo = loginState.result.userInfo as CloudUserInfo;
        this.globalData.userInfo = userInfo;
        this.globalData.hasUserInfo = true;
        this.globalData.isLoggedIn = true;
        
        // 保存用户信息到本地
        wx.setStorageSync('userInfo', userInfo);
      }
    } catch (err) {
      console.error('检查登录状态失败', err);
    }
  },
  
  // 与服务器同步用户信息
  async syncUserWithServer(localUserInfo: CloudUserInfo) {
    try {
      // 调用登录云函数，同步用户信息
      const loginResult = await wx.cloud.callFunction({
        name: 'login',
        data: {
          userInfo: {
            nickName: localUserInfo.nickName,
            avatarUrl: localUserInfo.avatarUrl,
            gender: localUserInfo.gender || 0,
            country: localUserInfo.country || '',
            province: localUserInfo.province || '',
            city: localUserInfo.city || ''
          }
        }
      });
      
      // @ts-ignore
      if (loginResult.result && loginResult.result.success) {
        // @ts-ignore
        const serverUserInfo = loginResult.result.userInfo as CloudUserInfo;
        // 如果服务器返回的用户信息不同，则更新本地缓存
        if (serverUserInfo && 
            (serverUserInfo.nickName !== localUserInfo.nickName || 
             serverUserInfo.avatarUrl !== localUserInfo.avatarUrl)) {
          console.log('用户信息已从服务器更新', serverUserInfo);
          this.globalData.userInfo = serverUserInfo;
          wx.setStorageSync('userInfo', serverUserInfo);
        }
      }
    } catch (error) {
      console.error('同步用户信息失败', error);
      // 同步失败不影响用户体验，只记录日志
    }
  }
});